package cn.iocoder.yudao.module.peizhen.service.opencity;

import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.infra.service.config.ConfigService;
import cn.iocoder.yudao.module.peizhen.dal.dataobject.opencity.ProgramDO;
import cn.iocoder.yudao.module.peizhen.dal.mysql.opencity.ProgramMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.module.peizhen.controller.admin.opencity.vo.*;
import cn.iocoder.yudao.module.peizhen.dal.dataobject.opencity.OpenCityDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.peizhen.dal.mysql.opencity.OpenCityMapper;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.peizhen.enums.ErrorCodeConstants.*;

/**
 * 服务开通城市 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OpenCityServiceImpl implements OpenCityService {

    @Resource
    private OpenCityMapper openCityMapper;

    @Resource
    private ConfigService configService;
    @Resource
    private ProgramMapper programMapper;

    @Override
    public Integer createOpenCity(OpenCitySaveReqVO createReqVO) {
        //修改open为1
        OpenCityDO openCityDO = openCityMapper.selectById(createReqVO.getId());
        if (openCityDO.getOpen()!=null&&openCityDO.getOpen()==1){
             throw exception(OPEN_CITY_HAS_EXISTS);
        }
        openCityDO.setOpen(1);
        openCityDO.setCreateTime(LocalDateTime.now());
        // 返回
        return   openCityMapper.updateById(openCityDO);
    }

    @Override
    public void updateOpenCity(OpenCitySaveReqVO updateReqVO) {
        // 校验存在
        validateOpenCityExists(updateReqVO.getId());
        // 更新
        OpenCityDO updateObj = BeanUtils.toBean(updateReqVO, OpenCityDO.class);
        openCityMapper.updateById(updateObj);
    }

    @Override
    public void deleteOpenCity(Integer id) {
        // 校验存在
        OpenCityDO openCityDO = openCityMapper.selectById(id);
        openCityDO.setOpen(0);
        openCityDO.setUpdateTime(LocalDateTime.now());
        openCityMapper.updateById(openCityDO);
    }

    private void validateOpenCityExists(Integer id) {
        if (openCityMapper.selectById(id) == null) {
            throw exception(OPEN_CITY_NOT_EXISTS);
        }
    }

    @Override
    public OpenCityDO getOpenCity(Integer id) {
        return openCityMapper.selectById(id);
    }

    @Override
    public PageResult<OpenCityDO> getOpenCityPage(OpenCityPageReqVO pageReqVO) {
        return openCityMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OpenCityDO> getAllCity() {
        List<OpenCityDO> openCityDOS = openCityMapper.selectList();
        return openCityDOS;
    }

    @Override
    public OpenCityDO fetchCityLocation(String longitude, String latitude) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        ConfigDO config = configService.getConfigByKey("gaode-key");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("key", config.getValue());
        paramMap.put("location", StringUtils.joinWith(",",longitude,latitude));
        String httpResult = HttpUtil.get("https://restapi.amap.com/v3/geocode/regeo", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(httpResult);
        Integer status=jsonObject.getInteger("status");
        if (status.equals(1)){
            String cityName = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getString("city");
            OpenCityDO openCityDO = openCityMapper.selectByName(cityName);
            return openCityDO;
        }
        return null;
    }

    // ==================== 子表（具体服务） ====================

    @Override
    public PageResult<ProgramDO> getProgramPage(PageParam pageReqVO, Integer cityCode) {
        return programMapper.selectPage(pageReqVO, cityCode);
    }

    @Override
    public Integer createProgram(ProgramDO program) {
        program.setPrice(program.getIsPrice()*100);
        program.setOriginalPrice(program.getOriginalPrice()*100);
        programMapper.insert(program);
        return program.getId();
    }

    @Override
    public void updateProgram(ProgramDO program) {
        // 校验存在
        validateProgramExists(program.getId());
        program.setPrice(program.getPrice()*100);
        program.setOriginalPrice(program.getOriginalPrice()*100);
        // 更新
        programMapper.updateById(program);
    }

    @Override
    public void deleteProgram(Integer id) {
        // 校验存在
        validateProgramExists(id);
        // 删除
        programMapper.deleteById(id);
    }

    @Override
    public ProgramDO getProgram(Integer id) {
        return programMapper.selectById(id);
    }

    private void validateProgramExists(Integer id) {
        if (programMapper.selectById(id) == null) {
            throw exception(PROGRAM_NOT_EXISTS);
        }
    }

    private void deleteProgramByCityCode(Integer cityCode) {
        programMapper.deleteByCityCode(cityCode);
    }

    @Override
    public List<ProgramDO> getProgramList(Integer cityCode,Integer projectId) {
        if (cityCode == null) {
            throw exception(OPEN_CITY_HAS_EXISTS);
        }
        List<ProgramDO> result=programMapper.selectList(
                new LambdaQueryWrapperX<ProgramDO>().eq(ProgramDO::getCityCode,cityCode).eqIfPresent(ProgramDO::getProjectId,projectId));
        return result;
    }
}